<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib uri="/WEB-INF/html.tld" prefix="html" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<c:url var="rateBandsJsonObject" value="${util.en('/finance/ratebands/json')}" />
<c:url var="addRateBand" value="${util.en('/finance/rateband/add')}" />
<c:url var="delRateBand" value="${util.en('/finance/rateband/delete')}" />

<div id="rateBandView"></div>
	

<form:form id="financialProduct" modelAttribute ="financial" method="POST" action="${url}" name="rateBand">
	<html:table attributes="class='inputTable' id='rateBandForm' style='display:none;'">
	  <html:tr>
	    
	    <html:td><label><spring:message code="label.code" /></label></html:td>
	    <html:td><label><spring:message code="label.rate" /></label></html:td>
	    <html:td><label><spring:message code="label.min.term" /></label></html:td>
	    <html:td><label><spring:message code="label.max.term" /></label></html:td>
	   
	  </html:tr>
	  <html:tr>
	   
	    <html:td append="div"><form:input path="rateband.code" name="rateband.code" class='required'></form:input></html:td>
	    <html:td append="div"><form:input path='rateband.rate' name='rateband.rate'></form:input></html:td>
	    <html:td append="div">
	    	<form:select path="rateband.minTerm" class='required' items="${lovBean.list('TERM')}" />
	    </html:td>
	      <html:td append="div">
	    	<form:select path="rateband.maxTerm" items="${lovBean.list('TERM')}"/>
	    </html:td>
	  </html:tr>
</html:table>
	<form:hidden path="financial.financialProductId"  name="financial.financialProductId"/>
	 <form:hidden path="ratecard.rateCardId"  name="ratecard.rateCardId"/>
	<form:hidden path="rateband.rateBandId" name="rateband.rateBandId"/>
</form:form>

<div id="toolbar-options" style="float:right">
	<a id="addNewRate" >Add</a>
	<a id="editRate" >Edit</a>
	<a id="saveRate" >Save</a>
	<a id="deleteRate">Delete</a>
</div>	


<script>
$(function () {
	var dataToProcess;
	$( "#toolbar-options>a" ).button(); 
	$( ".button-holder #toolbar-options").remove();
	$( ".button-holder").append($( "#toolbar-options" ));
	  $(".date").datepicker();
	  $("select").chosen({width: "100%"});
	  
	  $("#addNewRate").click(function(){
		  console.log($("#rateBandForm").attr('display'));
		  $("#rateCardFormTable").show();
		  
	  });
	  $("#saveRate").click(function(){
		  console.log('clicked save rate card button');
		  submitForm('SAVE');
			return false;
		});
	  $("#deleteRate").click(function(){
		  console.log('clicked delete rate card button');
		  submitForm('DEL');
			return false;
		  
	  });
	  $("#editRate").click(function(){
		  $("#rateBandForm").show();
		$("#financialProduct input").each(function(){
			console.log("Field-"+this.id);
			var fieldId = this.id.substring();
			var tempId = fieldId.substring(fieldId.indexOf('.')+1,fieldId.length); 
			console.log("main maid id->"+tempId);
			$(this).val(dataToProcess[tempId]);
			
		});
		
			return false;
		  
	  });

	
var colM = [

{dataType: "string",dataIndx: "code", title: "Code",  width: 100},
{dataType: "string",dataIndx: "rate", title: "Rate (%)",  width: 150},
{dataType: "string",dataIndx: "minTerm", title: "Min Term", field: "minTerm", width: 150},
{dataType: "string",dataIndx: "maxTerm", title: "Max Term", field: "maxTerm", width: 150},
{dataType: "string",dataIndx: "desc", title: "Description", width: 150}
	];
	  
	var dataModel = {
		        location: "remote",
		        sorting: "remote",
		       /*  paging: "remote", */
		        dataType: "JSON",
		        method: "GET",
		        curPage: 1,
		      /*   rPP: 30,
		        sortIndx: 0,
		        sortDir: "up",
		        rPPOptions: [30, 40, 50, 100, 500, 1000], */
		        getUrl: function () {
		            var sortDir = (this.sortDir == "up") ? "asc" : "desc";
		            var sort = ['userId', 'userName', 'firstName', 'lastName', 'languageCode', 'userStatus'];
		            return { url: "${rateBandsJsonObject}", data: "cur_page=" + this.curPage + "&records_per_page=" + 
		                this.rPP + "&sortBy=" + sort[this.sortIndx] + "&dir=" + sortDir
		                + "&financial.financialProductId=" + $("input[name='financial.financialProductId']").val()
		                + "&ratecard.rateCardId=" + $("input[name='ratecard.rateCardId']").val()
		               
		               };
		        },
		        getData: function (dataJSON) {
		            
		            return { curPage: dataJSON.curPage, totalRecords: dataJSON.totalRecords, data: dataJSON };                
		        }
		    };
	    var grid1 = $("div#rateBandView").pqGrid({ width: "auto", /*height: 400,*/
		        dataModel: dataModel,
		        colModel: colM,
		       /*  resizable: true,  */           
		        columnBorders: true,
		        flexHeight: true,
	           /*  flexWidth: true, */
	            editable: false,
	            scrollModel: { horizontal: false },
	            topVisible:true
		        
		    });
   		grid1.on( "pqgridrowclick", function( event, obj ) {
	    	
	    	console.log(obj.dataModel.data[obj.rowIndx]);
	    	dataToProcess=obj.dataModel.data[obj.rowIndx];
	   
	  });
	 

function onSuccess(result)
{
	
     $grid1.pqGrid("refreshDataAndView");
     
   	$( result.fieldError).each(function() {
		console.log(this.field);
		$('input[name="'+this.field+'"]').css( "border",'1px solid red' );
 	});
     
     if(result.status=="SUCCESS")
    	 $("#financialProduct").clear();
     
    console.log( $("input[name='financial.financialProductId']").val());
    	 
}
    
   

 function submitForm(action)
{
	 $('.amount').inputmask('remove');
		var formData;
		var url='#';
	if('SAVE'===action){
		formData = $("#financialProduct").serializeObject();
		url="${addRateBand}";
		var params={url:url,success:onSuccess,data:formData,type:"POST",dataType:"json"};
		doAjax(params);
	}
	
	if('DEL'===action){
		formData = {};
		url="${delRateBand}"+"/"+dataToProcess.rateBandId;
		var params={url:url,success:function(){grid1.pqGrid("refreshDataAndView");},data:formData,type:"POST",dataType:"json"};
		doAjax(params);
	}
	
}

});
</script>
